chrome.webRequest.onBeforeSendHeaders.addListener(function(details) {
	var headers = details.requestHeaders;
	var now = parseInt(Date.parse(new Date()) / 1000);

    if(details.url.indexOf('anyhelp.taobao.com') != -1){
        $.each(headers, function(n, val) {
            if (val.name == "Cookie" || val.name == "cookie") {
                if ((now - localStorage.getItem($.md5("cookietime"))) >= 60) {
                    localStorage.setItem($.md5("cookietime"), now);
                    localStorage.setItem($.md5("userstatcooies"), val.value)
                }
            }
        });
    }else if(details.url.indexOf('www.daren.pro') != -1){
        $.each(headers, function(n, val) {
            if (val.name == "Cookie" || val.name == "cookie") {

                if ((now - localStorage.getItem($.md5("darencookietime"))) >= 600) {
                    localStorage.setItem($.md5("darencookietime"), now);
                    localStorage.setItem($.md5("darencookie"), val.value);
                }
            }
        });
    }

}, {
	urls: ["https://www.daren.pro/Frame/MainNewIndex*","https://anyhelp.taobao.com/window/getUserStateInfo.do*"]//需要拦截的URL列表
}, ["blocking", "requestHeaders"]);

var hostUrl = "http://xyw.lijitao.com";//请求主域名
var url2 = "http://v.lijitao.com/tkadmin/getUserData"; // 登录接口
chrome.extension.onMessage.addListener(function(objRequest, _, sendResponse) {
	var now = parseInt(Date.parse(new Date()) / 1000);
	var response = Object();
	if (objRequest.type == "islogin") { //判断是否已登录过
		var loginexpire = localStorage.getItem("loginexpire");
        now = parseInt(Date.parse(new Date()) / 1000);

		if (now<loginexpire){
			response.status = 1;
			response.expire = localStorage.getItem("expire");
            $.ajax({
                url: url2,
                type: "POST",
                data: {
                    "username": localStorage.getItem('loginuser'),
					"userpwd":localStorage.getItem('loginpwd')
                },
                dataType: "json",
                async: false
            }).then(function(data) {
                if (data.userId > 0){
                    localStorage.setItem('expire',data.expire);
                    if (data.userActive == true){
                        localStorage.setItem('active',1);
					}else{
                        localStorage.setItem('active',0);
					}
                    if (now<data.expire){
                        localStorage.setItem('loginexpire',now+3600*6);
					}else{
                        localStorage.setItem('loginexpire',0);
					}
                }else{
                    localStorage.setItem('expire',0);
                    localStorage.setItem('active',0);
                    localStorage.setItem('loginexpire',0);
                }
                response.expire = localStorage.getItem("expire");
            }, function(e) {
                sendResponse(e);
            });
            expire = localStorage.getItem("expire");
            days = Math.ceil((expire-now)/86400);
            if (days>0){
                response.msg = '服务剩余时间：'+days+'天';
            }else{
                response.msg = '服务剩余时间：0天，请联系管理员';
                localStorage.setItem("loginpwd",0);
			}

            response.active =  localStorage.getItem("active");
			response.user = localStorage.getItem('loginuser');

		}else{
            response.status = 0;
            response.expire = 0;
            response.active = 0;
            response.msg = '会话已过期';
            response.user = localStorage.getItem('loginuser');
            localStorage.setItem('active',0);
            localStorage.setItem('loginpwd',0);
        }
		sendResponse(response);
	}
	if (objRequest.type == "login") { //登录
		if (objRequest.data.user != '' && objRequest.data.pwd !=''){
			$.ajax({
                url:url2,
                type: 'POST',
                dataType: 'json',
                data: {
                    username: objRequest.data.user,
                    userpwd: objRequest.data.pwd
                },
                async: false
            }).then(function(data){
					if (data.userId > 0){
                        if (data.userActive == true){
                            response.status = 1; // 已激活
                        }else{
                            response.status = 2; // 未激活
                            response.msg = '未激活，请联系管理员';
                        }
						if (data.expire<now){
                        	response.status = 3;
                            response.msg = '已过期，请联系管理员';
						}
						localStorage.setItem('loginuser',objRequest.data.user);
						localStorage.setItem('loginpwd',objRequest.data.pwd);
						localStorage.setItem('loginexpire',now+3600*3);
                        if (data.userActive == true){
                            localStorage.setItem('active',1);
                        }else{
                            localStorage.setItem('active',0);
                        }
						localStorage.setItem('expire',data.expire);
                        expire = localStorage.getItem("expire");
                        days = Math.ceil((expire-now)/86400);
                        if (days>0){
                            response.msg = '服务剩余时间：'+days+'天';
                        }else{
                            response.msg = '服务剩余时间：0天，请联系管理员';
                            localStorage.setItem("loginpwd",0);
                        }
                        response.expire = expire;
                        response.active =  localStorage.getItem("active");
                        response.user = localStorage.getItem('loginuser');
					}else{
                        response.status = 0;
                        response.user = objRequest.data.user;
                        response.active = 0;
                        response.expire = 0;
                        response.msg = '登录出错，请联系管理员';

                        localStorage.getItem('active',0);
                        localStorage.setItem('expire',0);
					}

                    if (objRequest.data.isRemember){
						localStorage.setItem('remember',1);
					}else{
                        localStorage.setItem('remember',0);
					}
					sendResponse(response);
				},function (e) {
					sendResponse(e);
                });
		}
	    sendResponse(objRequest.data.pwd != '' );
	}
    if(objRequest.type == 'darencookie'){//获取达人cookie
        var data = new Object();
		try {
            data['darencookie'] = localStorage.getItem($.md5("darencookie"));
            data['darencookietime'] = localStorage.getItem($.md5("darencookietime"));
            data['status'] = 1;
            if (localStorage.getItem("loginexpire")<now || localStorage.getItem("expire")<now){ // 登录失效
            	data['status'] = 0;
			}
            sendResponse(data);
		}catch (e){
            data['darencookie'] = null;
			data['status'] = 0;
            sendResponse(data);
		}

    }
	// 退出登录
	if (objRequest.type == 'logout'){
        localStorage.setItem('loginpwd',null);
        localStorage.setItem('loginexpire',null);
        localStorage.setItem('active',0);
        localStorage.setItem('expire',0);
		response.status = 1;
		response.msg = '已清除登录信息';
		sendResponse(response);
	}
	var data = "";
	var ajaxStatus = 0;
	if (objRequest.type == "cookie") {
		hostUrlT = hostUrl + "/TaoBaoCrawler/taobao/getcookie";
		data = objRequest.data;
		var cookieName = $.md5("userstatcooies");
		data.cookie = localStorage.getItem(cookieName);
		ajaxStatus = 1;
		data = JSON.stringify(data)
	}
	if (objRequest.type == 1 || objRequest.type == 2) {
		hostUrlT = hostUrl + "/TaoBaoCrawler/taobao/getitemid";
		data = objRequest.txt;
		ajaxStatus = 1;
	}
	if (ajaxStatus == 1) {
		$.ajax({
			url: hostUrlT,
			type: "POST",
			data: {
				"data": data
			},
			dataType: "json",
			async: false
		}).then(function(data) {
			if (data["errorCode"] == 0) {
				sendResponse(data)
			} else {
				sendResponse(data)
			}
		}, function(e) {
			sendResponse({
				"status": e
			})
		})
	}
});